"""
用户界面模块
包含所有UI相关的功能，如菜单绘制和事件处理
"""

import pygame
import os
import json
from settings import *

class UI:
    """用户界面类，处理所有UI相关的功能"""
    
    def __init__(self, game, map_editor=None):
        """初始化UI"""
        self.game = game
        self.map_editor = map_editor
        self.scroll_offset = 0

    def draw_main_menu(self):
        """绘制主菜单"""
        self.game.screen.fill(DARKGREY)
        title_rect = self.game.draw_text(TITLE, 64, WHITE, WIDTH / 2, HEIGHT / 4)
        
        # 绘制视野模式选择
        # 清晰模式选中时变绿，迷雾模式变灰；迷雾模式选中时变绿，清晰模式变灰
        fog_color = GREEN if FOG_OF_WAR else LIGHTGREY
        clear_color = GREEN if not FOG_OF_WAR else LIGHTGREY
        
        # 绘制模式选择标题
        self.game.draw_text("视野模式选择", 36, WHITE, WIDTH / 2, HEIGHT / 2 - 50)
        
        # 绘制模式按钮
        self.game.fog_btn = self.game.draw_text("迷雾模式", 36, fog_color, WIDTH / 2 - 150, HEIGHT / 2)
        self.game.clear_btn = self.game.draw_text("清晰模式", 36, clear_color, WIDTH / 2 + 150, HEIGHT / 2)
        
        # 绘制当前模式状态提示
        current_mode = "迷雾模式" if FOG_OF_WAR else "清晰模式"
        self.game.draw_text(f"当前模式: {current_mode}", 24, YELLOW, WIDTH / 2, HEIGHT / 2 + 50)
        
        # 绘制按钮
        self.game.play_btn = self.game.draw_text("Play Game", 48, GREEN, WIDTH / 2, HEIGHT / 2 + 100)
        self.game.ai_mode_btn = self.game.draw_text("AI Mode", 48, PURPLE, WIDTH / 2, HEIGHT / 2 + 170)
        self.game.editor_btn = self.game.draw_text("Map Editor", 48, BLUE, WIDTH / 2, HEIGHT / 2 + 240)
        self.game.quit_btn = self.game.draw_text("Quit", 48, RED, WIDTH / 2, HEIGHT / 2 + 310)

    def draw_map_selection_menu(self):
        """绘制地图选择菜单"""
        self.game.screen.fill(DARKGREY)
        self.game.draw_text("Select Map", 64, WHITE, WIDTH / 2, 50)
        
        # 获取所有地图文件
        map_files = self.game.get_map_files()
        
        # 计算可见区域
        item_height = 80
        visible_area_height = HEIGHT - 200  # 为标题和按钮留出空间
        items_per_page = max(1, visible_area_height // item_height)
        
        # 计算滚动范围
        total_height = len(map_files) * item_height
        max_scroll = max(0, total_height - visible_area_height)
        
        # 限制滚动偏移量
        self.scroll_offset = max(0, min(self.scroll_offset, max_scroll))
        
        # 显示地图列表
        self.game.map_buttons = []
        start_y = 150 - self.scroll_offset
        
        # 只显示可见的地图文件
        start_index = max(0, self.scroll_offset // item_height)
        end_index = min(len(map_files), start_index + items_per_page + 1)
        
        for i in range(start_index, end_index):
            map_file = map_files[i]
            y_pos = start_y + (i * item_height)
            
            # 只绘制在屏幕范围内的项目
            if y_pos > -item_height and y_pos < HEIGHT:
                # 绘制地图名称
                button = self.game.draw_text(map_file, 36, WHITE, WIDTH / 2, y_pos)
                self.game.map_buttons.append((button, map_file))
                
                # 绘制缩略图（简化版）
                self.draw_map_thumbnail(map_file, WIDTH / 2 - 150, y_pos - 15)
        
        # 绘制滚动指示器
        if max_scroll > 0:
            # 绘制滚动条背景
            scrollbar_bg = pygame.Rect(WIDTH - 20, 150, 10, visible_area_height)
            pygame.draw.rect(self.game.screen, LIGHTGREY, scrollbar_bg)
            
            # 计算滚动条位置和大小
            scrollbar_height = max(20, visible_area_height * (visible_area_height / total_height))
            scrollbar_pos = 150 + (self.scroll_offset / max_scroll) * (visible_area_height - scrollbar_height)
            
            # 绘制滚动条
            scrollbar = pygame.Rect(WIDTH - 20, scrollbar_pos, 10, scrollbar_height)
            pygame.draw.rect(self.game.screen, WHITE, scrollbar)
        
        # 返回按钮
        self.game.back_btn = self.game.draw_text("Back", 36, RED, WIDTH / 2, HEIGHT - 50)

    def draw_map_thumbnail(self, map_file, x, y):
        """绘制地图缩略图（简化版）"""
        try:
            map_path = os.path.join(MAPS_DIR, map_file)
            with open(map_path, 'r') as f:
                map_data = json.load(f)
            
            # 创建缩略图表面
            thumbnail_size = 50
            thumbnail = pygame.Surface((thumbnail_size, thumbnail_size))
            thumbnail.fill(LIGHTGREY)
            
            # 分别存储障碍物和野怪数据
            obstacles = []
            monsters = []
            
            # 分离障碍物和野怪数据
            for item in map_data:
                if item[0] == "obstacle":
                    obstacles.append(item[1:])  # 去掉类型标识
                elif item[0] == "monster":
                    monsters.append(item[1:])   # 去掉类型标识
            
            # 绘制障碍物（简化表示）
            for obstacle_data in obstacles[:10]:  # 只绘制前10个障碍物
                ox, oy, ow, oh = obstacle_data
                # 缩放到缩略图尺寸
                scale_x = thumbnail_size / WIDTH
                scale_y = thumbnail_size / HEIGHT
                rect = pygame.Rect(
                    ox * scale_x, 
                    oy * scale_y, 
                    max(1, ow * scale_x), 
                    max(1, oh * scale_y)
                )
                pygame.draw.rect(thumbnail, OBSTACLE_COLOR, rect)
            
            # 绘制野怪（用小圆点表示）
            for monster_data in monsters[:10]:  # 只绘制前10个野怪
                mx, my = monster_data
                # 缩放到缩略图尺寸
                scale_x = thumbnail_size / WIDTH
                scale_y = thumbnail_size / HEIGHT
                px = mx * scale_x
                py = my * scale_y
                # 绘制一个小圆点表示野怪
                pygame.draw.circle(thumbnail, RED, (int(px), int(py)), 2)
            
            # 绘制到屏幕
            self.game.screen.blit(thumbnail, (x, y))
            
            # 绘制边框
            pygame.draw.rect(self.game.screen, WHITE, (x, y, thumbnail_size, thumbnail_size), 1)
        except Exception as e:
            # 如果无法加载地图，绘制一个占位符
            pygame.draw.rect(self.game.screen, LIGHTGREY, (x, y, 50, 50))
            pygame.draw.rect(self.game.screen, WHITE, (x, y, 50, 50), 1)

    def draw_save_menu(self):
        """绘制保存选项菜单"""
        self.game.screen.fill(DARKGREY)
        self.game.draw_text("Save Map", 64, WHITE, WIDTH / 2, 50)
        
        # 获取所有地图文件
        map_files = self.game.get_map_files()
        
        # 计算可见区域
        item_height = 80
        visible_area_height = HEIGHT - 200  # 为标题和按钮留出空间
        items_per_page = max(1, visible_area_height // item_height)
        
        # 计算滚动范围
        total_height = len(map_files) * item_height
        max_scroll = max(0, total_height - visible_area_height)
        
        # 限制滚动偏移量
        self.scroll_offset = max(0, min(self.scroll_offset, max_scroll))
        
        # 显示地图列表（带缩略图）
        self.game.save_buttons = []
        start_y = 150 - self.scroll_offset
        
        # 只显示可见的地图文件
        start_index = max(0, self.scroll_offset // item_height)
        end_index = min(len(map_files), start_index + items_per_page + 1)
        
        for i in range(start_index, end_index):
            map_file = map_files[i]
            y_pos = start_y + (i * item_height)
            
            # 只绘制在屏幕范围内的项目
            if y_pos > -item_height and y_pos < HEIGHT:
                # 绘制地图名称
                button = self.game.draw_text(map_file, 36, WHITE, WIDTH / 2, y_pos)
                self.game.save_buttons.append(('overwrite', button, map_file))
                
                # 绘制缩略图（简化版）
                self.draw_map_thumbnail(map_file, WIDTH / 2 - 150, y_pos - 15)
        
        # 新建地图按钮
        self.game.new_map_btn = self.game.draw_text("Create New Map", 36, GREEN, WIDTH / 2, HEIGHT - 100)
        self.game.save_buttons.append(('new', self.game.new_map_btn, None))
        
        # 取消按钮
        self.game.cancel_btn = self.game.draw_text("Cancel", 36, RED, WIDTH / 2, HEIGHT - 50)
        self.game.save_buttons.append(('cancel', self.game.cancel_btn, None))

    def draw_input_map_name(self):
        """绘制输入地图名称界面"""
        self.game.screen.fill(DARKGREY)
        self.game.draw_text("Enter Map Name:", 64, WHITE, WIDTH / 2, HEIGHT / 4)
        
        # 绘制输入框
        input_box = pygame.Rect(WIDTH / 2 - 150, HEIGHT / 2 - 25, 300, 50)
        pygame.draw.rect(self.game.screen, WHITE, input_box, 2)
        
        # 绘制输入文本
        if self.map_editor:
            text_surf = self.game.draw_text(self.map_editor.input_text, 36, WHITE, WIDTH / 2, HEIGHT / 2)
        
        # 绘制确认按钮
        self.game.confirm_btn = self.game.draw_text("Confirm", 36, GREEN, WIDTH / 2, HEIGHT / 2 + 100)
        
        # 绘制取消按钮
        self.game.cancel_btn = self.game.draw_text("Cancel", 36, RED, WIDTH / 2, HEIGHT / 2 + 160)

    def main_menu_events(self, event):
        """处理主菜单事件"""
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # 检查视野模式选择
            if hasattr(self.game, 'fog_btn') and self.game.fog_btn.collidepoint(event.pos):
                # 切换到迷雾模式
                from settings import FOG_OF_WAR
                if not FOG_OF_WAR:
                    # 修改settings.py中的FOG_OF_WAR变量
                    self.update_fog_of_war_setting(True)
                    # 立即重新绘制界面以反映颜色变化
                    self.draw_main_menu()
                    pygame.display.flip()  # 立即更新显示
            elif hasattr(self.game, 'clear_btn') and self.game.clear_btn.collidepoint(event.pos):
                # 切换到清晰模式
                from settings import FOG_OF_WAR
                if FOG_OF_WAR:
                    # 修改settings.py中的FOG_OF_WAR变量
                    self.update_fog_of_war_setting(False)
                    # 立即重新绘制界面以反映颜色变化
                    self.draw_main_menu()
                    pygame.display.flip()  # 立即更新显示
            
            # 检查按钮点击
            elif hasattr(self.game, 'play_btn') and self.game.play_btn.collidepoint(event.pos):
                self.game.state = 'map_selection'  # 修改为先进入地图选择菜单
            elif hasattr(self.game, 'ai_mode_btn') and self.game.ai_mode_btn.collidepoint(event.pos):
                self.game.state = 'ai_menu'
            elif hasattr(self.game, 'editor_btn') and self.game.editor_btn.collidepoint(event.pos):
                self.game.state = 'editor'
                self.game.new()  # 初始化地图编辑器
            elif hasattr(self.game, 'quit_btn') and self.game.quit_btn.collidepoint(event.pos):
                self.game.quit()

    def map_selection_events(self, event):
        """处理地图选择菜单事件"""
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:  # 向上滚动
                self.scroll_offset = max(0, self.scroll_offset - 50)
            elif event.button == 5:  # 向下滚动
                # 获取所有地图文件
                map_files = self.game.get_map_files()
                item_height = 80
                visible_area_height = HEIGHT - 200
                total_height = len(map_files) * item_height
                max_scroll = max(0, total_height - visible_area_height)
                self.scroll_offset = min(max_scroll, self.scroll_offset + 50)
            elif event.button == 1:  # 左键点击
                # 检查按钮点击
                if hasattr(self.game, 'map_buttons'):
                    for btn_rect, map_file in self.game.map_buttons:
                        if btn_rect.collidepoint(event.pos):
                            # 加载选定的地图
                            self.game.current_map_file = os.path.join(MAPS_DIR, map_file)
                            self.game.state = 'game'
                            self.game.new()  # 初始化新游戏
                            return
                            
                if hasattr(self.game, 'back_btn') and self.game.back_btn.collidepoint(event.pos):
                    self.game.state = 'main_menu'

    def save_menu_events(self, event):
        """保存菜单事件处理"""
        # 处理鼠标滚轮事件
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:  # 向上滚动
                self.scroll_offset = max(0, self.scroll_offset - 50)
            elif event.button == 5:  # 向下滚动
                # 获取所有地图文件
                map_files = self.game.get_map_files()
                item_height = 80
                visible_area_height = HEIGHT - 200
                total_height = len(map_files) * item_height
                max_scroll = max(0, total_height - visible_area_height)
                self.scroll_offset = min(max_scroll, self.scroll_offset + 50)
            elif event.button == 1:  # 左键点击
                # 检查按钮点击
                for action, button, map_file in self.game.save_buttons:
                    if button.collidepoint(event.pos):
                        if action == 'overwrite':
                            if self.map_editor:
                                self.map_editor.overwrite_map(map_file)
                            return
                        elif action == 'new':
                            if self.map_editor:
                                self.map_editor.prompt_new_map_name()
                            return
                        elif action == 'cancel':
                            self.game.state = self.game.previous_state
                            return

    def update_fog_of_war_setting(self, fog_enabled):
        """更新settings.py中的迷雾模式设置"""
        try:
            # 读取settings.py文件
            with open('settings.py', 'r', encoding='utf-8') as f:
                lines = f.readlines()
            
            # 查找并更新FOG_OF_WAR设置
            for i, line in enumerate(lines):
                if line.strip().startswith('FOG_OF_WAR ='):
                    lines[i] = f"FOG_OF_WAR = {str(fog_enabled)}\n"
                    break
            
            # 写回文件
            with open('settings.py', 'w', encoding='utf-8') as f:
                f.writelines(lines)
            
            # 重新导入settings模块以应用更改
            import importlib
            import settings
            importlib.reload(settings)
            
            # 更新全局变量FOG_OF_WAR，确保UI立即使用新值
            globals()['FOG_OF_WAR'] = fog_enabled
            
            print(f"视野模式已切换到：{'迷雾模式' if fog_enabled else '清晰模式'}")
            
        except Exception as e:
            print(f"更新视野模式设置时出错：{e}")

    def input_map_name_events(self, event):
        """输入地图名称事件处理"""
        if event.type == pygame.KEYDOWN:
            if self.map_editor and self.map_editor.input_active:
                if event.key == pygame.K_RETURN:
                    self.map_editor.create_new_map_with_name(self.map_editor.input_text)
                elif event.key == pygame.K_BACKSPACE:
                    self.map_editor.input_text = self.map_editor.input_text[:-1]
                else:
                    # 添加字符到输入文本（限制长度）
                    if len(self.map_editor.input_text) < 20:
                        self.map_editor.input_text += event.unicode
        
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # 检查确认按钮点击
            if hasattr(self.game, 'confirm_btn') and self.game.confirm_btn.collidepoint(event.pos):
                if self.map_editor:
                    self.map_editor.create_new_map_with_name(self.map_editor.input_text)
            
            # 检查取消按钮点击
            if hasattr(self.game, 'cancel_btn') and self.game.cancel_btn.collidepoint(event.pos):
                self.game.state = 'save_menu'